package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * @author kk
 * #date 2024/6/23 16:06
 */
//token的工具类
public class JwtUtil {

    public static SecretKey secretKey = Keys.hmacShaKeyFor("agwUh4ltWOReMHscllv0Iyr3f6X$Lu17".getBytes());

    /*
    * 创建token
    *   token中保存登录用户的身份信息
    * */
    public static String createToken(String userName, Long userId){

        String token = Jwts.builder()

                //主题(token类型)
                .setSubject("lease_login")
                .setExpiration(new Date(System.currentTimeMillis() + 3600000 * 24 * 365))
                // claim  自定义数据
                .claim("userId", userId)
                .claim("userName", userName)
                //设置签名(防伪)
                .signWith(secretKey)
                .compact();

        return token;
    }

    /*
    * 解析token
    *   1.验证token是否过期
    *   2.可以从token中获取登录用户的信息
    * */
    public static Claims parseToken(String token){

        Jws<Claims> claimsJws = null;
        try {
            //根据签名解析token
            claimsJws = Jwts.parserBuilder()
                    .setSigningKey(secretKey)
                    .build().parseClaimsJws(token);
        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (Exception e){
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
        return claimsJws.getBody();
    }
}
